package com.pj.wisdomlogistics.mvp.frame;


import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.UnNetWorkException;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.rx.FilterSubscriber;
import com.pj.wisdomlogistics.rx.ResultFilter;

import java.lang.ref.WeakReference;
import java.util.Random;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by zhang on 2017/3/29.
 */

public class MvpPresenter <M extends MvpModel,V extends BaseView> {
    protected CompositeSubscription mCompositeSubscription;
    private WeakReference<V> mView;
    protected M mModel;
    private String modelKey;
    public void attachView(V v){
        mView = new WeakReference<V>(v);
        modelKey =String.valueOf(System.currentTimeMillis()+new Random().nextInt());
        mModel = (M) Mvp.getInstance().getModel(modelKey,Mvp.getGenericType(this,0));

    }


    protected V getView(){
        return mView.get();
    }
    protected M getModel(){
        return mModel;
    }
    public void onCreate() {

    }

    public void onResume() {

    }

    public void onPause() {

    }

    public void onDestroy() {
        unSubscribe();
    }

    public void onBackPressed() {
        unSubscribe();
    }


    //RXjava取消注册，以避免内存泄露
    public void unSubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.clear();
        }
    }


    protected void addSubscription(Observable observable, FilterSubscriber subscriber) {
        if(!MyApplication.isNetOk){
            subscriber.onError(new UnNetWorkException("网络连接断开"));
            return;
        }

        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .map(new ResultFilter())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    protected void addSubscription(Observable observable, Subscriber subscriber) {
        if(!MyApplication.isNetOk){
            subscriber.onError(new UnNetWorkException("网络连接断开"));
            return;
        }

        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .map(new ResultFilter())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

}
